//
//  BTMeVC.m
//  BaxTer
//
//  Created by 陈武琦 on 16/8/30.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "BTMeVC.h"
#import "TYVideoPlayerController.h"
#import "CWQ_MeTableHeaderView.h"
#import "BTMeCell.h"
#import "BTHospitalLearnCell.h"
#import "CWQ_collectionSegmentVC.h"
#import "BTCouseListVC.h"
#import "CWQ_HistoryLearnVC.h"
#import "BTDownloadVC.h"
#import "CWQ_settingVC.h"
#import "BTHaveLearntVC.h"
#import "CWQ_inegralVC.h"
#import "CWQ_userLevelVC.h"
#import "CWQ_MessageVC.h"
#import "BTLeaderBoardVC.h"
#import "BTNotifyReadM.h"
#import "UIButton+WebCache.h"
#import "BTHistoryCourseM.h"
#import "BTCourseDetailVC.h"
#import "BTCourseModel.h"
#import "UIView+WZLBadge.h"
#import "UIImageView+BTimageView.h"
#define headViewHeight cwqGetCustomHeight(130.0)

static NSString * const cellId = @"BTMeCellID";
static NSString * const hospitalLearnCellId = @"BTHospitalLearnCellID";
@interface BTMeVC ()<CWQ_MeTableHeaderViewDelegate, CWQ_hospitalLearnCellDelegate>


@property(nonatomic, strong) CWQ_MeTableHeaderView *headView;
@property(nonatomic, strong) UIImageView *headBGImageView;
@property(nonatomic, strong) UIButton *noticeBtn;
@property(nonatomic, strong) BTNotifyReadM *noticeM;
@property(nonatomic, strong) NSArray *learnHistoryCourses;
@end

@implementation BTMeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    //self.navigationController.navigationBar.alpha = 0.0;
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.tableView registerNib:[UINib nibWithNibName:@"BTMeCell" bundle:nil] forCellReuseIdentifier:cellId];
    [self.tableView registerNib:[UINib nibWithNibName:@"BTHospitalLearnCell" bundle:nil] forCellReuseIdentifier:hospitalLearnCellId];
    [self setupNavItems];
    [self setupTableHeadView];
    
   
  
    
}

- (void)setupNavItems {
    
    
    UIButton *settingBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 40, 40)];
    [settingBtn setImage:[UIImage imageNamed:@"设置"] forState:UIControlStateNormal];
    [settingBtn addTarget:self action:@selector(settingPress) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:settingBtn];
    
    
    UIButton *noticeBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 50, 20, 40, 40)];
    [noticeBtn setImage:[UIImage imageNamed:@"铃铛"] forState:UIControlStateNormal];
    [noticeBtn addTarget:self action:@selector(noticePress) forControlEvents:UIControlEventTouchUpInside];
   
    noticeBtn.badgeCenterOffset = CGPointMake(-16, 10);
    _noticeBtn = noticeBtn;
    [self.view addSubview:noticeBtn];

}

- (void)settingPress {
    
    CWQ_settingVC *settingVC = [CWQ_settingVC new];
    [self.navigationController pushViewController:settingVC animated:YES];
    
}

- (void)noticePress {
    CWQ_MessageVC *messageVC = [CWQ_MessageVC new];
    [self.navigationController pushViewController:messageVC animated:YES];
}


- (void)setupTableHeadView {
    NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"CWQ_MeTableHeaderView" owner:nil options:nil];
    _headView = [nibContents lastObject];
    _headView.delegate = self;
    [_headView setFrame:CGRectMake(0, 0, kScreenWidth, headViewHeight)];
    
    _headBGImageView = [[UIImageView alloc] initWithFrame:_headView.bounds];
    _headBGImageView.contentMode = UIViewContentModeScaleAspectFill;
    // 这个属性决定了子视图的显示范围 取值为YES时，剪裁超出父视图范围的子视图部分.这里就是裁剪了_pictureImageView超出_header范围的部分.
    _headBGImageView.clipsToBounds = YES;
    [_headBGImageView setImage:[UIImage imageNamed:@"背景"]];
    
    [_headView insertSubview:_headBGImageView atIndex:0];
    
    self.tableView.tableHeaderView = _headView;
    
}

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self requestNoticeData];
    [self requestHistoryLearnData];
    self.headView.userName.text = [HELAppManager userInfo].acname;
}

- (void)viewWillDisappear:(BOOL)animated {
    if ([self.navigationController viewControllers].count > 1) {
        
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
}


#pragma -mark- --------------------获取学习历史----------------------
- (void)requestHistoryLearnData {
    weakSelf_define;
    [[BTNetworkManager sharedMg] POST:BTStudyHistoryUrl parameters:nil success:^(id responseObject) {
        if ([responseObject[@"success"] boolValue]) {
            
            weakSelf.learnHistoryCourses = [BTHistoryCourseM mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"data"]];
            [weakSelf.tableView reloadData];
            
        }
    } failure:^(NSString *err) {
        
    }];
}



#pragma -mark- --------------------获取通知消息----------------------
- (void)requestNoticeData {

    weakSelf_define;
        [[BTNetworkManager sharedMg] POST:BTNotifyReadUrl parameters:nil success:^(id responseObject) {
            if (responseObject_success) {
                if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                    BTNotifyReadM *noticeM = [BTNotifyReadM mj_objectWithKeyValues:responseObject[@"data"]];
                    weakSelf.noticeM = noticeM;
                }
             
               
            }
        } failure:^(NSString *err) {

        }];

}

- (void)setNoticeM:(BTNotifyReadM *)noticeM {
    _noticeM = noticeM;
    UIView *hot = [self.noticeBtn viewWithTag:100];
    hot.hidden = self.noticeM.notReadNum.integerValue>0?NO:YES;
   self.noticeM.notReadNum.integerValue>0?[self.noticeBtn showBadgeWithStyle:WBadgeStyleRedDot value:1 animationType:WBadgeAnimTypeBreathe]:[self.noticeBtn clearBadge];
    self.noticeBtn.badgeCenterOffset = CGPointMake(-16, 10);
    if (self.noticeM.notReadNum.integerValue>0) {
        [self.noticeBtn resumeBadge];
    }else{
        [self.noticeBtn clearBadge];
    }
 
    [self.headView.headBtn sd_setImageWithURL:[NSURL URLWithString:noticeM.userImg] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"头像"]];

 
  
    self.headView.learned.text = [noticeM.readNum stringValue];
    self.headView.integral.text = [noticeM.score stringValue];
    [self.headView.practiceBtn setTitle:noticeM.levelName forState:UIControlStateNormal];
    [self.headView.practiceIcon bt_setImageWithUrl:noticeM.levelIcon];

}

#pragma mark - 滑动代理
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    /**
     *  这里的偏移量是纵向从contentInset算起 则一开始偏移就是0 向下为负 上为正 下拉
     */
    
    // 获取到tableView偏移量
    CGFloat Offset_y = scrollView.contentOffset.y;
    // 下拉 纵向偏移量变小 变成负的
    if ( Offset_y < 0) {
        // 拉伸后图片的高度
        CGFloat totalOffset = headViewHeight - Offset_y;
        // 图片放大比例
        CGFloat scale = totalOffset / headViewHeight;
        CGFloat width = kScreenWidth;
        // 拉伸后图片位置
        _headBGImageView.frame = CGRectMake(-(width * scale - width) / 2, Offset_y, width * scale, totalOffset);
    }
}

#pragma mark ----------------tableview代理--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 5;
    }
    return 0;
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        if (self.learnHistoryCourses.count > 0) {
            
            return 2;
        }
        return 1;
    }
    
    return 2;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0 && indexPath.row == 1) {
        BTHospitalLearnCell *cell = [tableView dequeueReusableCellWithIdentifier:hospitalLearnCellId forIndexPath:indexPath];
        cell.models = self.learnHistoryCourses;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
    
        return cell;
    }
    BTMeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    //设置cell 的分割线
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        cell.title.text = @"学习历史";
        if (self.learnHistoryCourses.count > 0) {
            
            [cell.rightIcon setImage:[UIImage imageNamed:@"down_icon"]];
        }
        [cell.leftIcon setImage:[UIImage imageNamed:@"学习历史 copy"]];
        return cell;
    }
    
    
    switch (indexPath.row) {
        case 0:
            cell.title.text = @"我的收藏";
            [cell.leftIcon setImage:[UIImage imageNamed:@"我的收藏"]];

            break;
        case 1:
            cell.title.text = @"下载文件";
            [cell.leftIcon setImage:[UIImage imageNamed:@"下载"]];
            break;
        default:
            break;
    }
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 1) {
        return 110;
    }
    return 44;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
        }
        CWQ_HistoryLearnVC *historyLearnVC = [[CWQ_HistoryLearnVC alloc] init];
        [self.navigationController pushViewController:historyLearnVC animated:YES];
    }else {
        
        switch (indexPath.row) {
            case 0:{
                
                CWQ_collectionSegmentVC *segmentVC = [[CWQ_collectionSegmentVC alloc] init];
                segmentVC.title = @"我的收藏";
                [self.navigationController pushViewController:segmentVC animated:YES];
                
            }
                break;
            case 1:{
                BTDownloadVC *downloadVC = [[BTDownloadVC alloc] init];
                [self.navigationController pushViewController:downloadVC animated:YES];
                
            }
                
                break;
                
            default:
                break;
        }
        
        
    }
}

#pragma mark------------------CWQ_MeTableHeaderViewDelegate----------------------------------
- (void)headView:(CWQ_MeTableHeaderView *)headView clickHeadBtn:(UIButton *)headBtn {
    CWQ_userLevelVC *userLevelVC = [CWQ_userLevelVC new];
    userLevelVC.avaterImg = self.noticeM.userImg;
   
   
    [self.navigationController pushViewController:userLevelVC animated:YES];
}

- (void)headView:(CWQ_MeTableHeaderView *)headView clickLearnedBtn:(UIButton *)headBtn {
    BTHaveLearntVC *learnVC = [[BTHaveLearntVC alloc] init];

    [self.navigationController pushViewController:learnVC animated:YES];
}


- (void)headView:(CWQ_MeTableHeaderView *)headView clickIntegralBtn:(UIButton *)headBtn {
    
    CWQ_inegralVC * inegralVC = [[CWQ_inegralVC alloc] init];
    inegralVC.score = [self.noticeM.score stringValue];
     inegralVC.leveliconUrl = self.noticeM.levelIcon;
    [self.navigationController pushViewController:inegralVC animated:YES];
    
}

- (void)headView:(CWQ_MeTableHeaderView *)headView clickTrainCampBtn:(UIButton *)headBtn {
    
}

- (void)headView:(CWQ_MeTableHeaderView *)headView leaderBoardBtn:(UIButton *)headBtn {

    BTLeaderBoardVC *leaderBoardVC = [BTLeaderBoardVC new];
    [self.navigationController pushViewController:leaderBoardVC animated:YES];

}

#pragma mark------------学习历史 点击------------

- (void)cwq_selectCell:(BTHospitalLearnCell *)cell model:(id)model{
    
    //根据model  设置跳转的条件
//    WSJLog(@"点击cell");
    BTCourseDetailVC *courseDetailVC = [BTCourseDetailVC new];
    BTCourseModel *courseM = (BTCourseModel *)model;
    courseDetailVC.courseId = [courseM.id integerValue];
    [self.navigationController pushViewController:courseDetailVC animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
